<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/10/31
 * Time: 15:08
 */
namespace app\admin\controller;

use app\AdminData\UserManageData;
use app\common\Common;
use think\Db;


/**
 * 会员管理
 * Class UserManage
 * @package app\admin\controller
 */
class UserManage extends Base
{
    /*会员缴费设置*/
    private $PConfig = ['user_shop', 'company_shop', 'entity_shop'];

    /*搜索条件*/
    private $SConfig = ['id', 'user_tel'];
    /*会员类型*/
    private $u_type = [1, 2, 3, 4, 5, 6];

    private $sortType = ['asc', 'desc'];

    private $userSort = ['create_time'];

    public function _initialize($str = null)
    {
        parent::_initialize($str); // TODO: Change the autogenerated stub
    }

    /**
     * 会员管理 title
     * @return \think\response\Json
     */
    public function title()
    {
        $user = new UserManageData();
        $end_time = time();
        $start_time = strtotime(date('Y-m-d', $end_time));
        $user_total = $user->getTodayUserNumber($start_time, $end_time);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'user_total' => Common::total("recover_status=0", "drh_user_info"),
                'shop_total' => Common::total("verify_status=1 and recover_status=0", "drh_shop"),
                'shop_entity_total' => Common::total("verify_status=1 and recover_status=0 and id_card >0", "drh_shop"),
                'original_user_total' => Common::total("verify_status=1 and recover_status=0", "drh_original_member"),
                'user_register' => $user_total
            ]
        ]);
    }

    /**
     * 会员缴费情况
     * @return \think\response\Json
     */
    public function userPaymentInfo()
    {
        $config = Common::getTableValue("drh_shop_payment_config", ['user_shop', 'company_shop', 'entity_shop'], 'id', 1);
        $data = new UserManageData();
        $time = strtotime(date('Y-m-d', time()));
        $payment = $data->userShopInfoPayment("effective_time_end >={$time} and status = 1");//缴纳的人数和钱
        $no_payment = $data->userShopInfoNoPayment("effective_time_end < {$time} and status != 0");//缴纳的人数和钱
        $no_payment = $this->countPM($no_payment, $config);

        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'shop_total' => Common::total("verify_status=1 and recover_status=0", "drh_shop"),
                'payment_people' => $payment['count'],
                'payment_money' => $payment['money'],
                'no_payment_people' => $no_payment['people'],
                'no_payment_money' => $no_payment['money'],
            ]
        ]);
    }

    private function countPM($res, $config)
    {
        $people = 0;
        $money = 0;
        foreach ($res as $k => $v) {
            if ($v['count'] == 0) continue;
            $people += $v['count'];
            switch ($v['type']) {
                case 0:
                    $money = $money + $v['count'] * $config['company_shop'];
                    break;
                case 1:
                    $money = $money + $v['count'] * $config['user_shop'];
                    break;
                case 2:
                    $money = $money + $v['count'] * $config['entity_shop'];
                    break;
                default :
                    break;
            }
        }
        return ['people' => $people, 'money' => $money];
    }

    /**
     * 会员缴费设置显示
     * @return \think\response\Json
     */
    public function showUserPaymentConfig()
    {
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => Common::getTableValue("drh_shop_payment_config", ['user_shop', 'company_shop', 'entity_shop'], 'id', 1)
        ]);
    }

    /**
     * 会员缴费设置修改
     * @param $key
     * @param $value
     * @return \think\response\Json
     */
    public function modifyUserPaymentConfig($key, $value)
    {
        if (!in_array(strtolower($key), $this->PConfig)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        if (!is_numeric($value) || $value < 0) {
            return json(['code' => $this->f_code, 'msg' => '设置的数值只能是数字并且小于0']);
        }
        $data = new UserManageData();
        $res = $data->modifyUserPaymentConfig($key, $value);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '修改成功!']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '系统繁忙请稍后在试!']);
        }
    }

    /**
     * 会员缴费查询
     * @param $key
     * @param $value
     * @param int $type
     * @return \think\response\Json
     */
    public function searchUserPayment($key, $value, $type = 1)
    {
        if (!in_array(strtolower($key), $this->SConfig)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        if (!is_numeric($value) || $value < 0) {
            return json(['code' => $this->f_code, 'msg' => '设置的数值只能是数字并且不能小于0']);
        }
        if ($type != 1 && $type != 2) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $data = new UserManageData();
        switch ($type) {
            case 2:
                return $this->NoPaymentInfo($key, $value, $data);
            default:
                return $this->PaymentInfo($key, $value, $data);
        }
    }

    private function PaymentInfo($key, $value, UserManageData $data)
    {
        $res = $data->PaymentInfo($key, $value);
        if (empty($res)) {
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => []]);
        }
        if ($res['shop_id'] == 0) {
            return json([
                'code' => $this->t_code,
                'msg' => 'OK',
                'data' => $res]);
        }
        $res['payment_flow'] = $data->getPaymentFlow($res['shop_id']);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res]);
    }

    private function NoPaymentInfo($key, $value, UserManageData $data)
    {
        $res = $data->PaymentInfo($key, $value);
        if (empty($res)) {
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => []]);
        }

        if ($res['shop_id'] == 0) return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => $res]);

        $shop_rule = $data->getShopRuleInfo($res['shop_id']);
        $time_start = time();
        $time = strtotime(date('Y-m-d', $time_start));
        if ($shop_rule['status'] == 0 || $shop_rule['effective_time_end'] > $time) {//不用交费或者已经交费完成的
            $res['money'] = 0;
        } else {//欠费情况
            $config = Common::getTableValue("drh_shop_payment_config", ['user_shop', 'company_shop', 'entity_shop'], 'id', 1);
            switch ($shop_rule['type']) {
                case 1:
                    $res['payment_flow']['money'] = $config['user_shop'];
                    break;
                case 2:
                    $res['payment_flow']['money'] = $config['company_shop'];
                    break;
                default:
                    $res['payment_flow']['money'] = $config['entity_shop'];
                    break;
            }
        }
        $res['payment_flow']['time'] = date('Y-m-d', $time_start);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res]);
    }


    /**
     * 会员列表显示
     * @param int $type
     * @param int $time_start
     * @param int $time_end
     * @param int $user_id
     * @param int $user_name
     * @param int $user_tel
     * @param int $page
     * @param int $pre
     * @return \think\response\Json
     */
    public function searchUserInfo($type = 1, $time_start = 0, $time_end = 0, $user_id = 0,
                                   $user_name = 0, $user_tel = 0, $page = 1, $pre = 15)
    {
        $sort = ['create_time' => 'desc'];
        if (!in_array(strtolower($type), $this->u_type)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $data = new UserManageData();
        if ($type == 4 || $type == 5 || $type == 3) {//店铺类型
            $where = $this->spliceWhere($time_start, $time_end, $user_id, $user_name, $user_tel, $title = 'b.');
//            $type -= 3;
//            $where .= " and a.shop_type={$type}";
            if ($type == 4) {
                $where .= " and id_card =''";
            } else if ($type == 5) {
                $where .= " and id_card > 0";
            }
            $res = $data->searchUserInfoShop($where, $page, $pre, $sort);
            $total = $data->getShopTotal($where);
        } else if ($type == 2 || $type == 6) {//普通会员
            if ($type == 6) $type = 1;
            $where = $this->spliceWhere($time_start, $time_end, $user_id, $user_name, $user_tel, $title = 'a.');
            $where .= "  and a.user_lv={$type}";
            $res = $data->searchUserInfoOrdinary($where, $page, $pre, $sort);
            $total = $data->searchUserInfoOrdinaryTotal($where, $sort);
            $total = empty($total) ? 0 : $total['count'];
        } else {//所有会员
            $where = $this->spliceWhere($time_start, $time_end, $user_id, $user_name, $user_tel, $title = 'a.');
            $res = $data->searchUserInfoAll($where, $page, $pre, $sort);
            $total = Common::total($where, "drh_user_info a");
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => empty($res) ? [] : $res,
                'total' => $total
            ]
        ]);
    }

    /**
     * 修改会员状态
     * @param $user_id
     * @param $status
     * @return \think\response\Json
     */
    public function editUserStatus($user_id, $status)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (!in_array($status, [0, 1])) {
            return json(['code' => $this->f_code, 'msg' => '状态错误']);
        }
        $data = new UserManageData();
        $data->editUserStatus($user_id, $status);
        return json(['code' => $this->t_code, 'msg' => '操作成功']);
    }

    public function editShopStatus($shop_id, $status)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        if (!in_array($status, [0, 1])) {
            return json(['code' => $this->f_code, 'msg' => '状态错误']);
        }
        $data = new UserManageData();
        $data->editShopStatus($shop_id, $status);
        return json(['code' => $this->t_code, 'msg' => '操作成功']);
    }

    private function spliceWhere($time_start, $time_end, $user_id, $user_name, $user_tel, $title = 'a.')
    {
        $where = "{$title}create_time >={$time_start}";
        $where = $time_end == 0 ? $where : $where . " and {$title}create_time<={$time_end}";
        $where = $user_id == 0 ? $where : $where . " and {$title}id ={$user_id}";
        $where = $user_tel == 0 ? $where : $where . " and {$title}user_tel = {$user_tel}";
        $where = $user_name === 0 ? $where : $where . " and {$title}user_name like '%{$user_name}%' ";
        return $where;
    }

    /**
     * 基本信息抬头
     * @param $user_id
     * @return \think\response\Json
     */
    public function showMemberInfoTitle($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $res = $data->showMemberInfoTitle($user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }

    /**
     * 基本信息
     * @param $user_id
     * @return \think\response\Json
     */
    public function showMemberInfoBase($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $shop_info = [];
        if (Common::checkTableFields('drh_shop', 'user_id', $user_id) == $this->t_code) {
            $shop_info = $data->getMemberShopInfo($user_id);
            $shop_info['img'] = json_decode($shop_info['img']);
        }
        $bank_info = $data->getMemberBankCard($user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'bank_info' => empty($bank_info) ? [] : $bank_info,
                'shop_info' => $shop_info
            ]
        ]);
    }

    /**
     * 积分收支记录 抬头
     * @param $user_id
     * @return \think\response\Json
     */
    public function showMemberIntegralIOTitle($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $integral = $data->showMemberIntegralIOTitle($user_id);
        $integral_in = 0;
        $integral_out = 0;
        foreach ($integral as $k => $v) {
            if ($v['integral'] < 0) {
                $integral_out = $v['integral'];
            }
            if ($v['integral'] > 0) {
                $integral_in = $v['integral'];
            }
        }
        $money_in = 0;
        $money_out = 0;
        $money = $data->showMemberMoneyIOTitle($user_id);
        foreach ($money as $k => $v) {
            if ($v['money'] < 0) {
                $money_out = $v['money'];
            }
            if ($v['money'] > 0) {
                $money_in = $v['money'];
            }

        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'integral_in' => $integral_in,
                'integral_out' => $integral_out,
                'money_in' => $money_in,
                'money_out' => $money_out,
            ]
        ]);
    }

    /**
     * 流水
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param int $type
     * @param int $time_start
     * @param int $time_end
     * @return \think\response\Json
     */
    public function searchMemberIntegralIO($user_id, $page = 1, $pre = 15, $type = 1, $time_start = 0, $time_end = 0)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $sort = ['create_time' => 'desc'];
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if ($type != 1 && $type != 2 && $type != 3) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        if (!is_numeric($time_start) || !is_numeric($time_end) || strlen($time_start) > 20 || strlen($time_end) > 20) {
            return json(['code' => $this->f_code, 'msg' => '搜索日期错误']);
        }
        $data = new UserManageData();
        $where = " a.create_time>={$time_start} and a.user_id={$user_id}";
        $where = $time_end == 0 ? $where : $where . " and a.create_time <={$time_end}";
        switch ($type) {
            case  2:
                $where = $where . " and ( a.money_expenses < 0 or (a.money_expenses =0 and a.integral_expenses <0))";
                break;
            case  3:
                $where = $where . " and ( a.money_expenses > 0 or (a.money_expenses =0 and a.integral_expenses >0))";
                break;
            default:
                break;
        }
        $res = $data->searchMemberIntegralIO($where, $page, $pre, $sort);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $res,
                'total' => Common::total($where, 'drh_user_flow a')
            ]
        ]);
    }

    /**
     * 积分交易明细
     * @param $order_num
     * @param $user_id
     * @return \think\response\Json
     */
    public function IntegralIOInfo($order_num, $user_id)
    {
        $res = Common::getTableValue('drh_user_flow', 'id', ['order_num', 'user_id'], [$order_num, $user_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该订单']);
        }
        $data = new UserManageData();
        $res = $data->IntegralIOInfo($order_num, $user_id);
        $title = substr($order_num, 0, 1);
        $total_money = 0;
        $proportion = 0;
        $integral_ratio = Common::getTableValue('drh_admin_config', 'value', 'name', 'integral_ratio');
        if ($title == 'o') {//商品交易
            $order_info = $data->getOrderInfo($order_num);
            $total_money = $order_info['total_price'] + $order_info['goods_freight'];
            if ($res['return_integral'] != 0) {
                $proportion = (($res['return_integral'] * $integral_ratio) / ($order_info['price'] + $order_info['freight_price'])) * 100;
            }
        } else {
            if ($res['money_expenses'] < 0) {
                $total_money -= $res['money_expenses'];
            }
            if ($res['integral_expenses'] < 0) {
                $total_money -= $res['integral_expenses'] * $integral_ratio;
            }
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'total_money' => $total_money,
                'proportion' => $proportion,
                'integral_expenses' => $res['integral_expenses'],
                'money_expenses' => $res['money_expenses'],
                'return_integral' => $res['return_integral'],
            ]
        ]);
    }

    /**
     * 积分质押记录
     * @param $user_id
     * @param int $type
     * @param int $page
     * @param int $pre
     * @param int $time_start
     * @param int $time_end
     * @return \think\response\Json
     */
    public function showIntegralPledge($user_id, $type = -1, $page = 1, $pre = 15, $time_start = 0, $time_end = 0)
    {
        if (Common::checkTableFields('drh_integral_withdraw', 'user_id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $sort = ['create_time' => 'desc'];
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (!in_array($type, [-1, 1, 3, 4])) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $where = " create_time>={$time_start} and user_id={$user_id}";
        $where = $time_end == 0 ? $where : $where . " and create_time <={$time_end}";
        $where = $type == -1 ? $where : $where . " and verify_status ={$type}";
        $data = new UserManageData();
        $res = $data->showIntegralPledge($where, $page, $pre, $sort);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $res,
                'total' => Common::total($where, 'drh_integral_withdraw')
            ]
        ]);
    }

    /**
     * 积分质押列表
     * @param $user_id
     * @param $order_num
     * @return \think\response\Json
     */
    public function showIntegralPledgeList($user_id, $order_num)
    {
        $res = Common::getTableValue('drh_integral_withdraw_flow', 'id', ['order_num_raw', 'user_id'], [$order_num, $user_id]);
        if (empty($res) && $res != 0) {
            return json(['code' => $this->f_code, 'msg' => '不存在该订单']);
        }
        $data = new UserManageData();
        $res = $data->showIntegralPledgeList($user_id, $order_num);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $res,
                'img' => Common::getTableValue('drh_integral_withdraw', 'img', 'order_num', $order_num)
            ]
        ]);
    }

    /**
     * 好友展示
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showUserFriend($user_id, $page = 1, $pre = 15, $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $data = new UserManageData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data->showUserFriend($user_id, $sort, $page, $pre),
                'total' => Common::total("user_id={$user_id}", 'drh_user_friend')
            ]
        ]);
    }

    /**
     * 审核申请
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @param  $type
     * @param  $time_start
     * @param  $time_end
     * @return \think\response\Json
     */
    public function showReviewApply($user_id, $type = -1, $page = 1, $pre = 15,
                                    $time_start = 0, $time_end = 0, $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (!in_array($type, [-1, 0, 1, 2])) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $pledge = $this->getIntegralPledgeReview($user_id, $page, $pre, $sort, $type, $time_start, $time_end);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'shop' => $this->getShopReview($type, $user_id, $page),
                'integral' => $pledge['pledge_review'],
                'total' => $pledge['total'] + 1
            ]
        ]);
    }

    /**
     * 店铺审核信息
     * @param $type
     * @param $user_id
     * @return array
     */
    private function getShopReview($type, $user_id, $page)
    {
        if ($page != 1) {
            return [];
        }
        if ($type == -1) {
            $res = Common::getTableValue('drh_shop', ['verify_status', 'shop_type', 'create_time', 'id'],
                ['user_id'], [$user_id]);
        } else {
            $res = Common::getTableValue('drh_shop', ['verify_status', 'shop_type', 'create_time', 'id'],
                ['user_id', 'verify_status'], [$user_id, $type]);
        }

        if (empty($res)) {
            $shop = [];
        } else {
            $shop = ['verify_status' => $res['verify_status'],
                'shop_type' => $res['shop_type'],
                'shop_id' => $res['id'],
                'create_time' => date('Y-m-d H:i:s', $res['create_time'])
            ];
        }
        return $shop;
    }

    /**
     * 积分质押信息
     * @param $user_id
     * @param $page
     * @param $pre
     * @param $sort
     * @param $type
     * @param $time_start
     * @param $time_end
     * @return array
     */
    private function getIntegralPledgeReview($user_id, $page, $pre, $sort, $type, $time_start, $time_end)
    {
        $data = new UserManageData();
        $where = "user_id={$user_id} and create_time >= {$time_start}";
        $where = $type == (-1) ? $where : $where . " and verify_status={$type}";
        $where = $time_end == 0 ? $where : $where . " and create_time <={$time_end}";
        return [
            'pledge_review' => $data->IntegralPledgeList($where, $page, $pre, $sort),
            'total' => Common::total($where, 'drh_integral_withdraw')
        ];
    }

    /**
     * 显示商户内容
     * @param $user_id
     * @param $shop_id
     * @return \think\response\Json
     */
    public function showShopInfo($user_id, $shop_id)
    {
        $res = Common::getTableValue('drh_shop', 'id', ['user_id', 'id'], [$user_id, $shop_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该申请']);
        }
        $data = new UserManageData();
        $res = $data->showShopInfo($user_id, $shop_id);
        $res['img'] = json_decode($res['img']);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }

    /**
     * 显示质押内容
     * @param $user_id
     * @param $order_num
     * @return \think\response\Json
     */
    public function showIntegralPledgeInfo($user_id, $order_num)
    {
        $res = Common::getTableValue('drh_integral_withdraw', 'id', ['user_id', 'order_num'], [$user_id, $order_num]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该申请']);
        }
        $data = new UserManageData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data->showIntegralPledgeInfo($user_id, $order_num)
        ]);
    }

    /**
     * 账号情况显示
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showUserMsgFlow($user_id, $page = 1, $pre = 15, $sort = ['create_time' => 'desc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (Common::checkTableFields('drh_user_msg_flow', 'user_id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data->showUserMsgFlow($user_id, $page, $pre, $sort),
                'total' => Common::total("user_id={$user_id}", 'drh_user_msg_flow')
            ]
        ]);
    }

    /**
     * 修改账号状态
     * @param $user_id
     * @param $type
     * @param $status
     * @param string $msg
     * @return \think\response\Json
     * @throws \Exception
     */
    public function changeUserStatus($user_id, $type, $status, $msg = '')
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (!in_array($type, [0, 1, 2])) {
            return json(['code' => $this->t_code, 'msg' => '类别错误']);
        }
        if ($status != 0 && $status != 1) {
            return json(['code' => $this->t_code, 'msg' => '状态错误']);
        }
        switch ($type) {
            case 0:
                $update = ['a.recover_status' => $status, 'b.recover_status' => $status];
                break;
            case 1:
                $update = ['a.recover_status' => $status];
                break;
            case 2:
                $update = ['b.recover_status' => $status];
                break;
            default:
                throw new \Exception("error:传递了错误的参数");
        }
        $data = new UserManageData();
        Db::startTrans();
        $res = $data->changeUserStatus($user_id, $update);
        if ($res) {
            if ($this->addUserMsgFlow($user_id, $type, $status, $data, $msg)) {
                Db::commit();
                return json(['code' => $this->t_code, 'msg' => '修改成功']);
            }
            Db::rollback();
            return json(['code' => $this->t_code, 'msg' => '系统繁忙请稍后在试']);
        } else {
            return json(['code' => $this->t_code, 'msg' => '修改失败']);
        }
    }

    /**
     * 添加消息
     * @param $user_id
     * @param $type
     * @param $status
     * @param UserManageData $data
     * @param $msg
     * @return int|string
     */
    public function addUserMsgFlow($user_id, $type, $status, UserManageData $data, $msg)
    {
        $time = time();
        return $data->addUserMsgFlow($user_id, $type, $status, $time, $msg);
    }

    /**
     * 代理显示
     * @param $user_id
     */
    public function incomeInfo($user_id)
    {

    }

    /**
     * 个人收益--->创始会员
     * @param $user_id
     * @return \think\response\Json
     */
    public function originalInfo($user_id)
    {
        $res = Common::getTableValue('drh_original_member', 'id', ['user_id', 'verify_status', 'recover_status'], [$user_id, 1, 0]);
        if (!empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '该会员不是创始会员']);
        }
        $data = new UserManageData();
        $res = $data->originalInfo($user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }

    /**
     * 代理信息
     * @param $user_id
     * @return \think\response\Json
     * @throws \Exception
     */
    public function areaProxyInfo($user_id)
    {
        $res = Common::getTableValue('drh_proxy', 'total_money', ['user_id', 'recover_status'], [$user_id, 0]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '该会员不是代理']);
        }
        $total_money = $res;
        $data = new UserManageData();
        $res = $data->areaProxyInfo($user_id);
        if (empty($res)) {
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => []]);
        }
        $proxy_money = $res['proxy_money'];//代理金额
        $where = "a.verify_status=1 and a.recover_status=0 ";
        switch ($res['type_lv']) {
            case 0:
                $where .= " and b.area_id={$res['area_id']}";
//                $recommend = round($total_money * config('region'));
                break;
            case 1://省
                $where .= " and b.province_id={$res['area_id']}";
//                $recommend = round($total_money * config('province'));
                break;
            case 2://市
                $where .= " and b.district_id={$res['area_id']}";
//                $recommend = round($total_money * config('city'));
                break;
            default :
                throw new \Exception("系统错误,请联系管理员");
        }

        $total = $data->areaProxyTotal($where);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'shop_total' => $total,
                'money' => $total_money,
                'recommend' => round($proxy_money * 0.1),
                'proxy_name' => $res['name'],
                'lv' => $res['type_lv']
            ]
        ]);
    }

    /**
     * 分销收益
     * @param $user_id
     * @return \think\response\Json
     */
    public function distributionIncomeInfo($user_id)
    {
        if (Common::checkTableFields('drh_user_friend', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $one_total = $data->oneDistributionTotal($user_id);
        $two_total = $data->twoDistributionTotal($user_id);
        $money = $data->distributionTotalMoney($user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'one' => $one_total,
                'two' => $two_total,
                'money' => $money,
            ]
        ]);
        //{"code":200,"msg":"OK","data":{"one":2,"two":2,"money":310}}
    }

    /**
     * 下级商铺
     * @param $user_id
     * @return \think\response\Json
     */
    public function shopProxyIncomeInfo($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $where = "a.user_id={$user_id} and c.total > 19 and c.status=1";
        $res = $data->shopProxyIncomeInfo($where);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'total' => $res,
                'money' => $res * 78 * 100
            ]
        ]);
    }

    public function subordinateProxy($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $res = $data->subordinateProxyTotal($user_id);
        if (empty($res)) {
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => []]);
        }
        switch ($res['type_lv']) {
            case 1:
                //省
                $city_id = substr($res['area_id'], 0, 2);
                $city_next_id = $city_id + 1;
                $city_next_id = $city_next_id . '0000';
                $total = $data->cityProxyTotal($city_id, $city_next_id);
                break;
            case 2:
                $total = 0;
                break;
            case 0:
                $total = 0;
                break;
            default:
                throw  new \Exception('类别错误error 404');
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'money' => $res['total_money'],
                'total' => $total
            ]
        ]);
    }

    /**
     * 创始会员个数
     * @param $user_id
     * @return \think\response\Json
     */
    public function originalMemberNext($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $data = new UserManageData();
        $res = $data->originalMemberNext($user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }

}